package com.cscj.android.repository.datastore

import android.content.Context
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.longPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import com.cscj.android.utils.endTimeOfDay
import com.cscj.android.utils.tomorrowTime
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.runBlocking
import java.util.UUID

class AppDataSourceImpl(context: Context) : AppDataStore {

    companion object {
        private val Context.appDataStore by preferencesDataStore("com.cssq.dataStore.appDataStore")
        private val keyPrivacyAgree = booleanPreferencesKey("privacyAgree")
        private val keyDeviceId = stringPreferencesKey("deviceId")
        private val keyAdBlockEndTime = longPreferencesKey("adBlockTime")

    }

    private val dataStore by lazy {
        context.appDataStore
    }

    override fun isPrivacyAgree(): Boolean {
        return runBlocking {
            dataStore.data.map {
                it[keyPrivacyAgree]
            }.firstOrNull() ?: false
        }
    }

    override suspend fun updatePrivacyAgree(agree: Boolean) {
        dataStore.edit {
            it[keyPrivacyAgree] = agree
        }
    }

    override suspend fun getDeviceId(): String {
        val deviceId = dataStore.data.map { it[keyDeviceId] }.firstOrNull()
        if (deviceId.isNullOrBlank()) {
            val generatedDeviceId = UUID.randomUUID().toString()
            dataStore.edit {
                it[keyDeviceId] = generatedDeviceId
            }
            return generatedDeviceId
        }
        return deviceId
    }

    override suspend fun updateBlockAdTime() {
        dataStore.edit {
            it[keyAdBlockEndTime] = endTimeOfDay(tomorrowTime())
        }
    }

    override fun showAdBlockEntry(): Flow<Boolean> {
        return dataStore.data.map {
            val blockTime = it[keyAdBlockEndTime] ?: 0L
            if (blockTime == 0L) {
                true
            } else {
                val now = System.currentTimeMillis()
                now > blockTime //结束时间
            }
        }
    }
}